<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>工程师工作台</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/css/all.min.css" rel="stylesheet">
<style>
        :root {
        --primary-color: #1890ff;
        --secondary-color: #2e5aac;
        --success-color: #52c41a;
        --info-color: #13c2c2;
        --warning-color: #faad14;
        --danger-color: #f5222d;
        --light-color: #f0f2f5;
        --dark-color: #001529;
        --border-color: #e8e8e8;
        --text-color: #333;
        --text-secondary: #666;
        }
        
        body {
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
        background-color: var(--light-color);
        color: var(--text-color);
            min-height: 100vh;
            display: flex;
            overflow-x: hidden;
        font-size: 14px;
        line-height: 1.5;
        }
        
    /* 侧边栏样式 - 简化 */
        .sidebar {
        width: 220px;
        background: var(--dark-color);
            min-height: 100vh;
            position: fixed;
            left: 0;
            top: 0;
            z-index: 100;
        box-shadow: 2px 0 6px rgba(0,0,0,0.1);
        }
        
        .sidebar-header {
        padding: 16px;
            text-align: center;
            border-bottom: 1px solid rgba(255,255,255,0.1);
        }
        
        .sidebar-header img {
        width: 50px;
        height: 50px;
            border-radius: 50%;
            object-fit: cover;
        border: 2px solid rgba(255,255,255,0.2);
        }
        
        .sidebar-header h4 {
            color: white;
        margin-top: 10px;
        font-size: 16px;
        font-weight: 500;
        }
        
        .sidebar-header p {
        color: rgba(255,255,255,0.65);
        font-size: 12px;
            margin-bottom: 0;
        }
        
        .sidebar-nav {
        padding: 8px 0;
        }
        
        .nav-item {
        padding: 0 12px;
        }
        
        .nav-link {
        color: rgba(255,255,255,0.65);
        padding: 10px 12px;
        border-radius: 4px;
            display: flex;
            align-items: center;
        margin: 4px 0;
        transition: all 0.2s;
        }
        
        .nav-link:hover, .nav-link.active {
            color: white;
        background-color: rgba(255,255,255,0.08);
        }
        
        .nav-link i {
        margin-right: 8px;
        width: 16px;
            text-align: center;
        }
        
    /* 主内容区域 - 精简 */
        .main-content {
            flex: 1;
        padding: 16px;
        margin-left: 220px;
        width: calc(100% - 220px);
        }
        
        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        margin-bottom: 16px;
        padding-bottom: 12px;
        border-bottom: 1px solid var(--border-color);
        }
        
        .page-title {
        font-size: 18px;
            font-weight: 600;
            margin: 0;
        }
        
    /* 工单列表卡片 - 更简洁 */
        .order-card {
            background-color: white;
        border-radius: 4px;
        padding: 16px;
        box-shadow: 0 1px 3px rgba(0,0,0,0.05);
        margin-bottom: 16px;
        }
        
        .table-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        margin-bottom: 16px;
        }
        
        .table-header h5 {
        font-size: 16px;
        font-weight: 500;
            margin: 0;
        }
        
        .table-actions {
            display: flex;
        gap: 8px;
        }
        
    /* 表格样式 - 更轻量 */
        .modern-table {
        width: 100%;
            border-collapse: separate;
            border-spacing: 0;
        font-size: 14px;
        }
        
        .modern-table th {
        background-color: #fafafa;
        color: var(--text-secondary);
        font-weight: 500;
        padding: 12px 8px;
        border-bottom: 1px solid var(--border-color);
        text-align: left;
        }
        
        .modern-table td {
        padding: 12px 8px;
        border-bottom: 1px solid var(--border-color);
            vertical-align: middle;
        }
        
        .modern-table tr:hover {
        background-color: #fafafa;
        }
        
        .modern-table .form-check-input {
            margin-top: 0;
        width: 16px;
        height: 16px;
        }
        
    /* 标签样式 - 更紧凑 */
        .tag {
            display: inline-block;
        padding: 2px 8px;
        border-radius: 2px;
            font-size: 12px;
        margin: 1px;
            color: white;
        }
        
        .tag-primary { background-color: var(--primary-color); }
        .tag-success { background-color: var(--success-color); }
        .tag-info { background-color: var(--info-color); }
        .tag-warning { background-color: var(--warning-color); }
        .tag-danger { background-color: var(--danger-color); }
        
    /* 按钮样式 - 更轻量 */
        .btn-custom {
        padding: 6px 12px;
        border-radius: 4px;
        font-weight: 400;
        font-size: 14px;
        transition: all 0.2s;
    }
    
    .btn-sm {
        padding: 4px 8px;
        font-size: 12px;
        }
        
        /* 打印样式优化 */
        @media print {
            @page {
                margin: 10mm;
            size: A4 landscape;
            }
            
            body {
                margin: 0 !important;
                padding: 0 !important;
                color: #000 !important;
                background: #fff !important;
            }
            
            table {
                page-break-inside: auto;
            }
            
            tr {
                page-break-inside: avoid;
            }
        }
        
        /* 响应式样式 */
        @media (max-width: 992px) {
            .sidebar {
            width: 60px;
            }
            
            .sidebar-header h4, .sidebar-header p, .nav-link span {
                display: none;
            }
            
            .sidebar-header img {
            width: 30px;
            height: 30px;
            }
            
            .main-content {
            margin-left: 60px;
            width: calc(100% - 60px);
            }
            
            .nav-link i {
                margin-right: 0;
            }
            
            .nav-item {
            padding: 0 5px;
            }
        }
        
        @media (max-width: 768px) {
            .sidebar {
                width: 0;
                opacity: 0;
            }
            
            .main-content {
                margin-left: 0;
                width: 100%;
            }
            
            .page-header {
                flex-direction: column;
                align-items: flex-start;
            }
            
            .page-title {
            margin-bottom: 8px;
        }
        
        .table-header {
            flex-direction: column;
            align-items: flex-start;
        }
        
        .table-actions {
            margin-top: 8px;
            }
    }

    /* 添加搜索框样式 */
    .search-box {
        width: 250px;
    }

    @media (max-width: 768px) {
        .search-box {
            width: 100%;
            margin-bottom: 8px;
        }
        
        .table-actions {
            flex-direction: column;
            width: 100%;
        }
        
        .table-actions button {
            margin-top: 5px;
        }
    }

    /* 添加结算金额和工单状态相关样式 */
    .settlement-amount {
        display: inline-block;
        padding: 3px 5px;
        border-radius: 2px;
        cursor: pointer;
    }

    .settlement-amount[data-editable="true"]:hover {
        background-color: #f0f0f0;
        border-bottom: 1px dashed #ccc;
    }

    .order-status {
        display: inline-block;
        padding: 2px 8px;
        border-radius: 2px;
        font-size: 12px;
        margin: 1px;
        color: white;
        cursor: pointer;
    }

    .order-status:hover {
        opacity: 0.8;
    }

    /* 统计卡片样式 */
    .stats-cards .card {
        box-shadow: 0 4px 10px rgba(0,0,0,0.07);
        transition: all 0.3s ease;
        overflow: hidden;
    }

    .stats-cards .card:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 20px rgba(0,0,0,0.1);
    }

    .stat-card {
        display: flex;
        align-items: center;
        padding: 20px;
        position: relative;
        z-index: 1;
        border-radius: 8px;
    }

    .stat-icon {
        font-size: 2.5rem;
        opacity: 0.8;
        margin-right: 15px;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 60px;
        height: 60px;
        border-radius: 50%;
        background-color: rgba(255,255,255,0.2);
    }

    .stat-content {
        flex: 1;
    }

    .stat-content h3 {
        font-size: 24px;
        font-weight: 600;
        margin: 0 0 5px 0;
        color: #fff;
    }

    .stat-content p {
        margin: 0;
        font-size: 14px;
        opacity: 0.85;
        color: #fff;
    }

    .stat-primary {
        background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
    }

    .stat-success {
        background: linear-gradient(135deg, var(--success-color) 0%, #3f9c35 100%);
    }

    .stat-info {
        background: linear-gradient(135deg, var(--info-color) 0%, #0e9b9b 100%);
    }

    .stat-warning {
        background: linear-gradient(135deg, var(--warning-color) 0%, #d69008 100%);
    }

    .stat-card::after {
        content: '';
        position: absolute;
        top: -20px;
        right: -20px;
        background: rgba(255,255,255,0.1);
        width: 100px;
        height: 100px;
        border-radius: 50%;
        z-index: -1;
    }

    .stat-card::before {
        content: '';
        position: absolute;
        bottom: -20px;
        left: -20px;
        background: rgba(255,255,255,0.1);
        width: 60px;
        height: 60px;
        border-radius: 50%;
        z-index: -1;
    }

    @media (max-width: 768px) {
        .stat-card {
            padding: 15px;
        }
        
        .stat-icon {
            font-size: 1.8rem;
            width: 45px;
            height: 45px;
            margin-right: 10px;
        }
        
        .stat-content h3 {
            font-size: 18px;
        }
        
        .stat-content p {
            font-size: 12px;
        }
    }

    /* 在style标签内添加工程师备注样式 */
    .engineer-note {
        display: inline-block;
        padding: 3px 5px;
        border-radius: 2px;
        cursor: pointer;
        color: var(--text-color);
    }

    .engineer-note:hover {
        background-color: #f0f0f0;
        color: var(--primary-color);
    }
</style>
</head>
<body>
    <!-- 侧边导航栏 -->
    <div class="sidebar">
        <div class="sidebar-header">
            <img src="/assets/img/avatar.png" alt="{$engineer.name|htmlentities}">
            <h4>{$engineer.name|htmlentities}</h4>
            <p>{$engineer.area}</p>
        </div>
        <div class="sidebar-nav">
            <ul class="nav flex-column">
                <li class="nav-item">
                    <a class="nav-link active" href="{:url('index/index')}">
                        <i class="fas fa-tachometer-alt"></i>
                        <span>控制台</span>
                    </a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="{:url('user/logout')}">
                        <i class="fas fa-sign-out-alt"></i>
                        <span>退出登录</span>
                    </a>
                </li>
            </ul>
                            </div>
                        </div>

    <!-- 主内容区域 -->
    <div class="main-content">
        <div class="page-header">
            <h1 class="page-title">
                <i class="fas fa-clipboard-list me-2"></i>工程师工作台
            </h1>
        </div>
        
        <!-- 数据统计卡片 -->
        <div class="row stats-cards mb-4">
            <div class="col-md-3 col-sm-6 mb-3">
                <div class="card border-0 h-100">
                    <div class="card-body stat-card stat-primary">
                        <div class="stat-icon"><i class="fas fa-check-circle"></i></div>
                        <div class="stat-content">
                            <h3>{$statistics.completed_count}</h3>
                            <p>已完工工单数</p>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-3 col-sm-6 mb-3">
                <div class="card border-0 h-100">
                    <div class="card-body stat-card stat-success">
                        <div class="stat-icon"><i class="fas fa-yen-sign"></i></div>
                        <div class="stat-content">
                            <h3>￥{$statistics.total_amount}</h3>
                            <p>结算金额总数</p>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-3 col-sm-6 mb-3">
                <div class="card border-0 h-100">
                    <div class="card-body stat-card stat-info">
                        <div class="stat-icon"><i class="fas fa-tools"></i></div>
                        <div class="stat-content">
                            <h3>{$statistics.installation_count}</h3>
                            <p>送装业务数量(总计)</p>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-md-3 col-sm-6 mb-3">
                <div class="card border-0 h-100">
                    <div class="card-body stat-card stat-warning">
                        <div class="stat-icon"><i class="fas fa-truck"></i></div>
                        <div class="stat-content">
                            <h3>{$statistics.delivery_count}</h3>
                            <p>配送业务数量(总计)</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 工单列表 -->
        <div class="order-card">
            <div class="table-header">
                <h5>
                    <i class="fas fa-list me-2"></i>
                    我的工单列表
                    {notempty name="orders"}
                    <span class="badge bg-primary ms-1">{:count($orders)}</span>
                    {/notempty}
                </h5>
                <div class="table-actions">
                    <!-- 添加搜索输入框 -->
                    <div class="search-box me-2">
                        <div class="input-group">
                            <input type="text" id="searchInput" class="form-control" placeholder="输入关键词搜索...">
                            <button class="btn btn-outline-secondary" type="button" id="clearSearchBtn">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                    </div>
                    <button id="printSelectedBtn" class="btn btn-outline-primary btn-custom" disabled>
                        <i class="fas fa-print me-1"></i>打印所选
                    </button>
                    <button id="exportSelectedBtn" class="btn btn-outline-success btn-custom" disabled>
                        <i class="fas fa-file-export me-1"></i>导出数据
                    </button>
                </div>
            </div>
            
            <!-- 添加搜索结果提示 -->
            <div id="searchResultInfo" class="alert alert-info py-1 px-2 mb-2" style="display:none;">
                搜索结果: <span id="resultCount">0</span> 条记录
            </div>
            
                        {empty name="orders"}
            <div class="text-center py-4">
                <i class="fas fa-clipboard text-muted" style="font-size: 36px;"></i>
                <p class="mt-2 text-muted">暂无工单数据</p>
                <button class="btn btn-primary btn-custom mt-2" id="refreshDataBtn">
                    <i class="fas fa-sync-alt me-1"></i>刷新数据
                </button>
            </div>
                        {else/}
            <div class="table-responsive">
                <table class="modern-table">
                                <thead>
                                    <tr>
                            <th width="40">
                                    <input class="form-check-input" type="checkbox" id="selectAll">
                            </th>
                                        <th>订单号</th>
                                        <th>业务类型</th>
                            <th>客户信息</th>
                            <th>收货地址</th>
                            <th>商品名称</th>
                            <th>总数量</th>
                            <th>工单状态</th>
                            <th>结算金额</th>
                            <th>标签</th>
                            <th>工程师备注</th>
                            <th width="80">操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {foreach name="orders" item="order"}
                        <tr>
                            <td>
                                    <input class="form-check-input order-checkbox" type="checkbox" value="{$order.id}">
                            </td>
                            <td>
                                <strong>{$order['订单号']|default='--'}</strong>
                            </td>
                                        <td>{$order['业务类型']|default='--'}</td>
                            <td>
                                <div>{$order['收货人名称']|default='--'}</div>
                                <small class="text-muted">{$order['收货人虚拟电话']|default=$order['收货人电话1']}</small>
                            </td>
                                        <td>{$order['收货人详细地址']|default='--'}</td>
                            <td>{$order['商品名称']|default='--'}</td>
                            <td>{$order['总数量']|default='--'}</td>
                            <td>
                                <span class="order-status tag tag-{$order['工单状态'] == '已完工' ? 'success' : 'warning'}" 
                                      data-order-id="{$order.id}" 
                                      data-status="{$order['工单状态']|default='待完工'}" 
                                      style="cursor:pointer;">
                                    {$order['工单状态']|default='待完工'}
                                </span>
                            </td>
                            <td>
                                <span class="settlement-amount" 
                                      data-order-id="{$order.id}" 
                                      data-amount="{$order['结算金额']|default='0.00'}" 
                                      data-editable="{$order['工单状态'] == '已完工' ? 'true' : 'false'}">
                                    ￥{$order['结算金额']|default='0.00'}
                                </span>
                            </td>
                            <td>
                                {php}
                                // 检查是否存在标签
                                $tagStr = isset($order['标签']) ? $order['标签'] : '';
                                // 如果包含逗号则分割，否则作为单个标签处理
                                $tagsRaw = $tagStr ? (strpos($tagStr, ',') !== false ? explode(',', $tagStr) : [$tagStr]) : [];
                                // 过滤空标签
                                $tags = [];
                                foreach($tagsRaw as $t) {
                                    $t = trim($t);
                                    if(!empty($t)) {
                                        $tags[] = $t;
                                    }
                                }
                                // 标签颜色
                                $colors = ['primary', 'success', 'info', 'warning', 'danger'];
                                {/php}
                                
                                {if condition="!empty($tags)"}
                                    {foreach name="tags" item="tag" key="k"}
                                        {php}
                                        $colorIndex = $k % count($colors);
                                        $colorClass = $colors[$colorIndex];
                                        {/php}
                                        <span class="tag tag-{$colorClass}">{$tag|htmlentities}</span>
                                    {/foreach}
                                {else/}
                                    <span class="text-muted">--</span>
                                {/if}
                            </td>
                            <td>
                                <span class="engineer-note" 
                                      data-order-id="{$order.id}" 
                                      data-note="{$order['工程师备注']|default=''}"
                                      style="cursor:pointer;">
                                    {$order['工程师备注']|default='--'|mb_substr=0,10}
                                    {if condition="isset($order['工程师备注']) && mb_strlen($order['工程师备注']) > 10"}...{/if}
                                </span>
                            </td>
                            <td>
                                <div class="d-flex">
                                    <button type="button" class="btn btn-primary btn-sm" onclick="viewOrderDetail('{$order.id}')">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                </div>
                                        </td>
                                    </tr>
                                    {/foreach}
                                </tbody>
                            </table>
            </div>
            {/empty}
    </div>
</div>

<!-- 订单详情模态框 -->
<div class="modal" id="orderDetailModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-file-alt me-2"></i> 工单详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="orderDetailContent">
                <!-- 内容将通过JS动态填充 -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="fas fa-times me-1"></i>关闭
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 工单状态修改模态框 - 优化版 -->
<div class="modal" id="orderStatusModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-light">
                <h5 class="modal-title"><i class="fas fa-tasks me-2"></i> 修改工单状态</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-4">
                <input type="hidden" id="statusOrderId">
                <div class="row mb-4">
                    <div class="col-md-12">
                        <label class="form-label fw-bold">工单状态</label>
                        <select class="form-select form-select-lg" id="orderStatusSelect">
                            <option value="待完工">待完工</option>
                            <option value="已完工">已完工</option>
                        </select>
                    </div>
                </div>
                
                <div class="row" id="settlementAmountGroup" style="display: none;">
                    <div class="col-md-12">
                        <div class="card bg-light">
                            <div class="card-body">
                                <label class="form-label fw-bold">结算金额 (￥)</label>
                                <div class="input-group input-group-lg">
                                    <span class="input-group-text">￥</span>
                                    <input type="number" class="form-control" id="settlementAmountInput" min="0" step="0.01" placeholder="请输入结算金额">
                                </div>
                                <div class="form-text text-muted mt-2">
                                    <i class="fas fa-info-circle me-1"></i>仅当工单状态为"已完工"时可修改结算金额
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                    <i class="fas fa-times me-1"></i>取消
                </button>
                <button type="button" class="btn btn-primary btn-lg" id="saveOrderStatus">
                    <i class="fas fa-save me-1"></i>保存
                </button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
// 用于存储工单数据的全局变量
var orderData = <?php echo json_encode($orders ?? []); ?>;
var currentOrderId = null;

// 全新打印管理器
var PrintManager = {
    createPrintView: function(orderIds) {
        if (!orderIds || orderIds.length === 0) {
            alert('请至少选择一个工单');
            return;
        }
        
        // 获取订单数据
        var orderDetails = [];
        for (var i = 0; i < orderIds.length; i++) {
            var order = findOrderById(orderIds[i]);
            if (order) {
                orderDetails.push(order);
            }
        }
        
        if (orderDetails.length === 0) {
            alert('未找到有效工单数据');
            return;
        }
        
        // 打开新窗口并生成打印预览
        var printWindow = window.open('', 'print_preview', 'width=800,height=600,scrollbars=yes');
        
        if (!printWindow) {
            alert('打印预览功能被阻止，请允许弹窗。');
            return;
        }
        
        var printContent = '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8">' +
            '<title>工单列表打印</title>' +
            '<style>' +
            'body{font-family:Arial,"Microsoft YaHei",sans-serif;font-size:13px;line-height:1.4;color:#111;margin:0;padding:8px}' +
            '.print-document{max-width:800px;margin:0 auto}' +
            '.company-info{display:flex;align-items:center;margin-bottom:8px}' +
            '.logo-box{width:36px;height:36px;background-color:#1890ff;color:white;display:flex;align-items:center;justify-content:center;font-weight:bold;font-size:14px;margin-right:8px;border-radius:2px}' +
            '.document-title{text-align:center;font-size:18px;font-weight:bold;margin:10px 0}' +
            '.print-table{width:100%;border-collapse:collapse;margin-bottom:10px;font-size:13px}' +
            '.print-table th,.print-table td{border:1.5px solid #888;padding:6px;text-align:center;color:#000}' +
            '.print-table th{background-color:#f0f0f0;font-weight:bold;text-align:center}' +
            '.print-controls{background-color:#f8f9fa;border-radius:4px;padding:6px;margin-bottom:10px;display:flex;justify-content:space-between;align-items:center}' +
            '.btn{display:inline-block;padding:4px 8px;font-size:12px;border-radius:3px;cursor:pointer;margin-left:5px;border:1px solid transparent}' +
            '.btn-primary{color:#fff;background-color:#1890ff;border-color:#1890ff}' +
            '.btn-secondary{color:#fff;background-color:#6c757d;border-color:#6c757d}' +
            '.summary{text-align:right;font-size:13px;margin-top:5px;color:#444;font-weight:bold}' +
            // 完全禁止打印URL
            '@media print {' +
            '  * {-webkit-print-color-adjust: exact !important; print-color-adjust: exact !important;}' +
            '  .print-controls{display:none !important}' +
            '  .print-document{max-width:100% !important}' +
            '  .print-table{border-collapse:collapse !important}' +
            '  .print-table th,.print-table td{border:2px solid #000 !important; text-align:center !important}' +
            '  a, a:link, a:visited {text-decoration: none !important; color: inherit !important}' +
            '  a[href]:after, a[href^="javascript:"]:after, a[href^="#"]:after {content: "" !important}' +
            '  abbr[title]:after {content: "" !important}' +
            '}' +
            '</style>' +
            '</head><body>' +
            '<div class="print-document">' +
            '<div class="print-controls">' +
            '<h3 style="margin:0;font-size:14px;">工单打印预览 (' + orderDetails.length + '条)</h3>' +
            '<div>' +
            '<button class="btn btn-secondary" onclick="window.close()">关闭</button>' +
            '<button class="btn btn-primary" onclick="window.print()">打印</button>' +
            '</div></div>' +
            '<div style="text-align:center"><h2 style="margin:0;font-size:16px;font-weight:bold">安德物流配送面单</h2>' +
            '<p style="margin:0;color:#666;font-size:12px">逻界工单处理系统</p></div>' +
            '<h1 class="document-title">工单列表</h1>' +
            '<table class="print-table"><thead><tr>' +
            '<th width="60">业务类型</th>' +
            '<th width="60">客户</th><th width="80">联系电话</th><th>收货地址</th><th>商品名称</th>' +
            '<th width="50">总数量</th>' +
            '<th width="100">信息员备注</th>' +
            '<th width="100">工程师备注</th>' +
            '</tr></thead><tbody>';
        
        // 添加数据行
        for (var i = 0; i < orderDetails.length; i++) {
            var order = orderDetails[i];
            var orderNote = order.信息员备注 || '暂无备注';
            var engineerNote = order.工程师备注 || '暂无备注';
            printContent += '<tr><td>' + (order.业务类型 || '--') + 
                '</td><td>' + (order.收货人名称 || '--') + 
                '</td><td>' + (order.收货人虚拟电话 || order.收货人电话1 || '--') + 
                '</td><td>' + (order.收货人详细地址 || '--') + 
                '</td><td>' + (order.商品名称 || '--') + 
                '</td><td>' + (order.总数量 || '--') + 
                '</td><td>' + orderNote + 
                '</td><td>' + engineerNote + '</td></tr>';
        }
        
        printContent += '</tbody></table>' +
            '<div class="summary">总计: ' + orderDetails.length + '条记录</div>' +
            '</div></body></html>';
        
            printWindow.document.open();
            printWindow.document.write(printContent);
            printWindow.document.close();
            printWindow.focus();
    },
    
    // 打印单个工单详情，修改为只显示详情而不打印
    printOrderDetail: function(orderId) {
        var order = findOrderById(orderId);
        if (!order) {
            alert('找不到该工单信息');
            return;
        }
        
        // 创建模态窗口显示工单详情
        var modal = new bootstrap.Modal(document.getElementById('orderDetailModal'));
        var modalContent = document.getElementById('orderDetailContent');
        
        // 构建详情HTML
        var detailHtml = '<div class="p-2">' +
            '<div class="mb-3"><h6>基本信息</h6>' +
            '<table class="table table-bordered table-sm">' +
            '<tr><th width="20%">订单号</th><td>' + (order.订单号 || '--') + '</td></tr>' +
            '<tr><th>业务类型</th><td>' + (order.业务类型 || '--') + '</td></tr>' +
            '<tr><th>商品名称</th><td>' + (order.商品名称 || '--') + '</td></tr>' +
            '<tr><th>总数量</th><td>' + (order.总数量 || '--') + '</td></tr>' +
            '<tr><th>工单状态</th><td>' + 
                '<span class="tag tag-' + (order.工单状态 === '已完工' ? 'success' : 'warning') + '">' + 
                (order.工单状态 || '待完工') + '</span></td></tr>' +
            '<tr><th>结算金额</th><td>￥' + (order.结算金额 || '0.00') + '</td></tr>' +
            '</table></div>' +
            
            '<div class="mb-3"><h6>收货人信息</h6>' +
            '<table class="table table-bordered table-sm">' +
            '<tr><th width="20%">收货人</th><td>' + (order.收货人名称 || '--') + '</td></tr>' +
            '<tr><th>联系电话</th><td>' + (order.收货人虚拟电话 || order.收货人电话1 || '--') + '</td></tr>' +
            '<tr><th>详细地址</th><td>' + (order.收货人详细地址 || '--') + '</td></tr>' +
            '</table></div>' +
            
            '<div class="mb-3"><h6>备注信息</h6>' +
            '<table class="table table-bordered table-sm">' +
            '<tr><th width="20%">信息员备注</th><td>' + (order.信息员备注 || '<span class="text-muted">暂无备注</span>') + '</td></tr>' +
            '<tr><th width="20%">工程师备注</th><td>' + 
                '<div class="input-group">' +
                '<textarea class="form-control" id="engineerNoteInput" rows="2">' + (order.工程师备注 || '') + '</textarea>' +
                '<button class="btn btn-primary" id="saveEngineerNote" data-order-id="' + order.id + '"><i class="fas fa-save"></i></button>' +
                '</div>' +
                '</td></tr>' +
            '</table></div>';
        
        // 设置模态框内容并显示
        modalContent.innerHTML = detailHtml;
        modal.show();
        
        // 移除打印按钮相关代码
        var printBtn = document.querySelector('#printDetailBtn');
        if (printBtn) {
            printBtn.remove();
        }
    }
};

function findOrderById(id) {
    for (var i = 0; i < orderData.length; i++) {
        if (orderData[i].id == id) {
            return orderData[i];
        }
    }
    return null;
}

// 查看工单详情
function viewOrderDetail(orderId) {
    PrintManager.printOrderDetail(orderId);
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 绑定刷新数据按钮
    var refreshDataBtn = document.getElementById('refreshDataBtn');
    if (refreshDataBtn) {
        refreshDataBtn.addEventListener('click', function() {
            // 显示加载图标
            this.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>正在刷新...';
            this.disabled = true;
            
            // 刷新当前页面
            window.location.reload();
        });
    }
    
    // 绑定打印选中按钮
    var printSelectedBtn = document.getElementById('printSelectedBtn');
    if (printSelectedBtn) {
        printSelectedBtn.addEventListener('click', function() {
            var selectedIds = [];
            document.querySelectorAll('.order-checkbox:checked').forEach(function(checkbox) {
                selectedIds.push(checkbox.value);
            });
            
            if (selectedIds.length === 0) {
                alert('请至少选择一个工单');
                return;
            }
            
            PrintManager.createPrintView(selectedIds);
        });
    }
    
    // 全选/取消全选
    var selectAllCheckbox = document.getElementById('selectAll');
    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', function() {
            var checkboxes = document.querySelectorAll('.order-checkbox');
            checkboxes.forEach(function(checkbox) {
                checkbox.checked = this.checked;
            }, this);
            updateButtonStatus();
        });
    }
    
    // 单个复选框更改时更新按钮状态和全选框状态
    var checkboxes = document.querySelectorAll('.order-checkbox');
    checkboxes.forEach(function(checkbox) {
        checkbox.addEventListener('change', function() {
            updateButtonStatus();
            updateSelectAllStatus();
        });
    });

    // 添加搜索功能
    var searchInput = document.getElementById('searchInput');
    var clearSearchBtn = document.getElementById('clearSearchBtn');
    var searchResultInfo = document.getElementById('searchResultInfo');
    var resultCountSpan = document.getElementById('resultCount');
    
    // 搜索功能实现
    function performSearch() {
        var searchText = searchInput.value.toLowerCase().trim();
        var tableRows = document.querySelectorAll('.modern-table tbody tr');
        var visibleCount = 0;
        
        // 没有搜索词则显示所有行
        if (searchText === '') {
            tableRows.forEach(function(row) {
                row.style.display = '';
            });
            searchResultInfo.style.display = 'none';
            return;
        }
        
        // 有搜索词则过滤
        tableRows.forEach(function(row) {
            var rowText = row.textContent.toLowerCase();
            if (rowText.includes(searchText)) {
                row.style.display = '';
                visibleCount++;
            } else {
                row.style.display = 'none';
            }
        });
        
        // 显示搜索结果数量
        resultCountSpan.textContent = visibleCount;
        searchResultInfo.style.display = 'block';
        
        // 更新全选框状态和按钮状态
        updateSelectAllStatus();
        updateButtonStatus();
    }
    
    // 绑定搜索事件
    if (searchInput) {
        searchInput.addEventListener('input', performSearch);
        searchInput.addEventListener('keydown', function(e) {
            if (e.key === 'Enter') {
                performSearch();
            }
        });
    }
    
    // 清除搜索
    if (clearSearchBtn) {
        clearSearchBtn.addEventListener('click', function() {
            searchInput.value = '';
            performSearch();
        });
    }

    // 工程师备注点击事件 - 直接打开编辑模式
    var noteElements = document.querySelectorAll('.engineer-note');
    if (noteElements) {
        noteElements.forEach(function(element) {
            element.addEventListener('click', function() {
                var orderId = this.getAttribute('data-order-id');
                viewOrderDetail(orderId);
            });
        });
    }

    // 在模态框显示后绑定保存备注事件
    document.getElementById('orderDetailModal').addEventListener('shown.bs.modal', function () {
        var saveNoteBtn = document.getElementById('saveEngineerNote');
        if (saveNoteBtn) {
            saveNoteBtn.addEventListener('click', function() {
                var orderId = this.getAttribute('data-order-id');
                var note = document.getElementById('engineerNoteInput').value.trim();
                
                // 发送AJAX请求保存工程师备注
                var xhr = new XMLHttpRequest();
                xhr.open('POST', '{:url("user/updateEngineerNote")}', true);
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                xhr.onload = function() {
                    if (xhr.status === 200) {
                        try {
                            var res = JSON.parse(xhr.responseText);
                            if (res.code === 1) {
                                // 更新成功，更新页面数据
                                var noteElement = document.querySelector('.engineer-note[data-order-id="' + orderId + '"]');
                                if (noteElement) {
                                    // 更新备注显示，超过10个字符显示...
                                    var displayText = note;
                                    if (note.length > 10) {
                                        displayText = note.substring(0, 10) + '...';
                                    } else if (note.length === 0) {
                                        displayText = '--';
                                    }
                                    noteElement.textContent = displayText;
                                    noteElement.setAttribute('data-note', note);
                                }
                                
                                // 更新本地数据
                                for (var i = 0; i < orderData.length; i++) {
                                    if (orderData[i].id == orderId) {
                                        orderData[i].工程师备注 = note;
                                        break;
                                    }
                                }
                                
                                // 显示成功提示
                                alert('备注保存成功');
                            } else {
                                // 更新失败
                                alert('保存失败: ' + res.msg);
                            }
                        } catch (e) {
                            alert('响应解析错误，请刷新页面重试');
                        }
                    }
                };
                xhr.onerror = function() {
                    alert('网络错误，请稍后重试');
                };
                xhr.send('order_id=' + orderId + '&engineer_note=' + encodeURIComponent(note));
            });
        }
    });
});

// 重写updateButtonStatus函数，考虑搜索过滤
function updateButtonStatus() {
    var checkedCount = document.querySelectorAll('.order-checkbox:checked:not([style*="display: none"])').length;
    var printBtn = document.getElementById('printSelectedBtn');
    var exportBtn = document.getElementById('exportSelectedBtn');
    
    if (printBtn) {
        printBtn.disabled = checkedCount === 0;
        printBtn.innerHTML = '<i class="fas fa-print me-1"></i>打印所选' + (checkedCount > 0 ? ' (' + checkedCount + ')' : '');
    }
    
    if (exportBtn) {
        exportBtn.disabled = checkedCount === 0;
        exportBtn.innerHTML = '<i class="fas fa-file-export me-1"></i>导出' + (checkedCount > 0 ? ' (' + checkedCount + ')' : '');
    }
}

// 重写updateSelectAllStatus函数，考虑搜索过滤
function updateSelectAllStatus() {
    var allCheckboxes = document.querySelectorAll('.order-checkbox:not([style*="display: none"])');
    var checkedCheckboxes = document.querySelectorAll('.order-checkbox:checked:not([style*="display: none"])');
    var selectAllCheckbox = document.getElementById('selectAll');
    
    if (allCheckboxes.length > 0 && checkedCheckboxes.length === allCheckboxes.length) {
        selectAllCheckbox.checked = true;
        selectAllCheckbox.indeterminate = false;
    } else if (checkedCheckboxes.length === 0) {
        selectAllCheckbox.checked = false;
        selectAllCheckbox.indeterminate = false;
    } else {
        selectAllCheckbox.indeterminate = true;
    }
}

// 修改全选功能，只选择可见行
var selectAllCheckbox = document.getElementById('selectAll');
if (selectAllCheckbox) {
    selectAllCheckbox.addEventListener('change', function() {
        var checkboxes = document.querySelectorAll('.order-checkbox:not([style*="display: none"])');
        checkboxes.forEach(function(checkbox) {
            checkbox.checked = this.checked;
        }, this);
        updateButtonStatus();
    });
}

// 处理工单状态点击事件
document.addEventListener('DOMContentLoaded', function() {
    // 工单状态点击事件
    var statusElements = document.querySelectorAll('.order-status');
    if (statusElements) {
        statusElements.forEach(function(element) {
            element.addEventListener('click', function() {
                var orderId = this.getAttribute('data-order-id');
                var status = this.getAttribute('data-status');
                
                // 设置模态框值
                document.getElementById('statusOrderId').value = orderId;
                document.getElementById('orderStatusSelect').value = status;
                
                // 根据状态决定是否显示结算金额输入框
                if (status === '已完工') {
                    document.getElementById('settlementAmountGroup').style.display = 'block';
                    // 获取当前行的结算金额
                    var amountElement = document.querySelector('.settlement-amount[data-order-id="' + orderId + '"]');
                    var amount = amountElement.getAttribute('data-amount');
                    document.getElementById('settlementAmountInput').value = amount;
                } else {
                    document.getElementById('settlementAmountGroup').style.display = 'none';
                }
                
                // 显示模态框
                var modal = new bootstrap.Modal(document.getElementById('orderStatusModal'));
                modal.show();
            });
        });
    }
    
    // 工单状态选择事件
    var statusSelect = document.getElementById('orderStatusSelect');
    if (statusSelect) {
        statusSelect.addEventListener('change', function() {
            var status = this.value;
            if (status === '已完工') {
                document.getElementById('settlementAmountGroup').style.display = 'block';
            } else {
                document.getElementById('settlementAmountGroup').style.display = 'none';
            }
        });
    }
    
    // 保存工单状态按钮点击事件
    var saveStatusBtn = document.getElementById('saveOrderStatus');
    if (saveStatusBtn) {
        saveStatusBtn.addEventListener('click', function() {
            var orderId = document.getElementById('statusOrderId').value;
            var status = document.getElementById('orderStatusSelect').value;
            var amount = document.getElementById('settlementAmountInput').value;
            
            // 发送AJAX请求更新工单状态
            var xhr = new XMLHttpRequest();
            xhr.open('POST', '{:url("user/updateOrderStatus")}', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
            xhr.onload = function() {
                if (xhr.status === 200) {
                    var res = JSON.parse(xhr.responseText);
                    if (res.code === 1) {
                        // 更新成功，关闭模态框并更新页面数据
                        var statusElement = document.querySelector('.order-status[data-order-id="' + orderId + '"]');
                        var amountElement = document.querySelector('.settlement-amount[data-order-id="' + orderId + '"]');
                        
                        if (statusElement) {
                            statusElement.textContent = status;
                            statusElement.setAttribute('data-status', status);
                            
                            // 更新标签样式
                            if (status === '已完工') {
                                statusElement.className = 'order-status tag tag-success';
                            } else {
                                statusElement.className = 'order-status tag tag-warning';
                            }
                        }
                        
                        if (amountElement && status === '已完工') {
                            amountElement.textContent = '￥' + amount;
                            amountElement.setAttribute('data-amount', amount);
                            amountElement.setAttribute('data-editable', 'true');
                        } else if (amountElement) {
                            amountElement.setAttribute('data-editable', 'false');
                        }
                        
                        // 关闭模态框
                        var modal = bootstrap.Modal.getInstance(document.getElementById('orderStatusModal'));
                        modal.hide();
                        
                        // 显示成功消息
                        alert('工单状态更新成功');
                    } else {
                        // 更新失败
                        alert('更新失败: ' + res.msg);
                    }
                }
            };
            xhr.onerror = function() {
                alert('网络错误，请稍后重试');
            };
            xhr.send('order_id=' + orderId + '&status=' + encodeURIComponent(status) + '&amount=' + amount);
        });
    }
    
    // 结算金额行内编辑
    var amountElements = document.querySelectorAll('.settlement-amount');
    if (amountElements) {
        amountElements.forEach(function(element) {
            element.addEventListener('click', function() {
                var editable = this.getAttribute('data-editable');
                if (editable !== 'true') {
                    return;
                }
                
                var orderId = this.getAttribute('data-order-id');
                var currentAmount = this.getAttribute('data-amount');
                
                // 创建输入框
                var input = document.createElement('input');
                input.type = 'number';
                input.className = 'form-control form-control-sm';
                input.value = currentAmount;
                input.min = '0';
                input.step = '0.01';
                input.style.width = '100px';
                
                // 替换当前元素
                var parent = this.parentNode;
                parent.replaceChild(input, this);
                input.focus();
                
                // 添加事件处理
                input.addEventListener('blur', function() {
                    var newAmount = this.value;
                    if (newAmount === '') {
                        newAmount = '0.00';
                    }
                    
                    // 发送AJAX请求更新结算金额
                    var xhr = new XMLHttpRequest();
                    xhr.open('POST', '{:url("user/updateOrderStatus")}', true);
                    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                    xhr.onload = function() {
                        if (xhr.status === 200) {
                            var res = JSON.parse(xhr.responseText);
                            if (res.code === 1) {
                                // 创建新的span元素
                                var span = document.createElement('span');
                                span.className = 'settlement-amount';
                                span.setAttribute('data-order-id', orderId);
                                span.setAttribute('data-amount', newAmount);
                                span.setAttribute('data-editable', 'true');
                                span.textContent = '￥' + newAmount;
                                
                                // 替换输入框
                                parent.replaceChild(span, input);
                                
                                // 添加点击事件
                                span.addEventListener('click', function() {
                                    var editable = this.getAttribute('data-editable');
                                    if (editable !== 'true') {
                                        return;
                                    }
                                    
                                    var orderId = this.getAttribute('data-order-id');
                                    var currentAmount = this.getAttribute('data-amount');
                                    
                                    var input = document.createElement('input');
                                    input.type = 'number';
                                    input.className = 'form-control form-control-sm';
                                    input.value = currentAmount;
                                    input.min = '0';
                                    input.step = '0.01';
                                    input.style.width = '100px';
                                    
                                    var parent = this.parentNode;
                                    parent.replaceChild(input, this);
                                    input.focus();
                                    
                                    // 重新绑定事件（递归调用）
                                    input.addEventListener('blur', arguments.callee);
                                });
                            } else {
                                alert('更新失败: ' + res.msg);
                                // 恢复原始显示
                                var span = document.createElement('span');
                                span.className = 'settlement-amount';
                                span.setAttribute('data-order-id', orderId);
                                span.setAttribute('data-amount', currentAmount);
                                span.setAttribute('data-editable', 'true');
                                span.textContent = '￥' + currentAmount;
                                
                                parent.replaceChild(span, input);
                            }
                        }
                    };
                    xhr.onerror = function() {
                        alert('网络错误，请稍后重试');
                        // 恢复原始显示
                        var span = document.createElement('span');
                        span.className = 'settlement-amount';
                        span.setAttribute('data-order-id', orderId);
                        span.setAttribute('data-amount', currentAmount);
                        span.setAttribute('data-editable', 'true');
                        span.textContent = '￥' + currentAmount;
                        
                        parent.replaceChild(span, input);
                    };
                    xhr.send('order_id=' + orderId + '&status=已完工&amount=' + newAmount);
                });
                
                // 处理回车键
                input.addEventListener('keypress', function(e) {
                    if (e.key === 'Enter') {
                        this.blur();
                    }
                });
            });
        });
    }
});
</script>
</body>
</html> 